<template>
  <view class="info-container">
    <!-- 基础信息标题 -->
    <view class="section-title">
      <text class="title-text">基础信息</text>
    </view>

    <!-- 表单内容 -->
    <view class="form-section">
      <!-- 姓名 -->
      <view class="base-form-item" :class="{ active: !formData.userInfo?.real_name && isSubmit }">
        <view class="base-label-box">
          <text class="label">姓名</text>
          <text class="required">*</text>
          <text class="fail-label" v-if="!formData.userInfo?.real_name && isSubmit">请填写姓名</text>
        </view>
        <input 
          class="input" 
          type="text" 
          v-model="formData.userInfo.real_name" 
          placeholder="请输入姓名"
          placeholder-style="color: #B5B5B5"
          @input="nameInputChange"
        />
      </view>

      <!-- 身份证号 -->
      <view class="base-form-item" :class="{ active: !validateIdCard(formData.userInfo?.idnum) && isSubmit }">
        <view class="base-label-box">
          <text class="label">身份证号</text>
          <text class="required">*</text>
          <text class="fail-label" v-if="!validateIdCard(formData.userInfo?.idnum) && isSubmit">请填写正确的身份证号</text>
        </view>
        <input 
          class="input" 
          type="idcard" 
          v-model="formData.userInfo.idnum" 
          placeholder="请输入身份证号"
          placeholder-style="color: #B5B5B5"
          @input="idCardInputChange"
        />
      </view>

      <!-- 手机号 -->
      <view class="base-form-item">
        <view class="base-label-box">
          <text class="label">手机号 (不可修改)</text>
        </view>
        <text class="phone-text">{{formatPhone(formData.userInfo?.phone)}}</text>
      </view>

      <!-- 性别 -->
      <view class="form-gender-group-item">
        <view class="base-label-box">
          <text class="label">性别</text>
        </view>
        <view class="gender-group">
          <view 
            class="gender-item" 
            :class="{ active: formData.userInfo?.gender === '1' }"
            @click="formData.userInfo.gender = '1'"
          >
            <text>男</text>
          </view>
          <view 
            class="gender-item" 
            :class="{ active: formData.userInfo?.gender === '2' }"
            @click="formData.userInfo.gender = '2'"
          >
            <text>女</text>
          </view>
          <view 
            class="gender-item" 
            :class="{ active: formData.userInfo?.gender === '0' }"
            @click="formData.userInfo.gender = '0'"
          >
            <text>保密</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 资质信息标题 -->
    <view class="section-title">
      <text class="title-text">资质信息</text>
    </view>
    
    <!-- 资质信息内容 -->
    <view class="form-section">
      <!-- 其他证书 -->
      <template v-for="(item, key) in certList" :key="key">
        <view class="cert-form-item">
          <view class="cert-label-box">
            <text class="label">{{ item.label }}</text>
          </view>
          <view class="cert-group">
            <view 
              class="cert-item" 
              :class="{ active: formData.userInfo[key] === '1' }"
              @click="formData.userInfo[key] = '1' "
            >有</view>
            <view 
              class="cert-item" 
              :class="{ active: formData.userInfo[key] === '0' }"
              @click="formData.userInfo[key] = '0'"
            >无</view>
          </view>
        </view>
      </template>
    </view>

    <!-- 证明材料标题 -->
    <view class="section-title">
      <text class="title-text">证明材料</text>
    </view>

    <!-- 证明材料上传区 -->
    <view class="form-section">
      <view class="upload-section">
        <text class="upload-title">请上传附件信息</text>
        <view class="upload-area">
          <view class="upload-preview" v-for="(img, index) in imageList" :key="index">
            <image :src="img" mode="aspectFill"></image>
            <view class="delete-btn" @click="deleteImage(index)">×</view>
          </view>
          <view class="upload-btn" @click="chooseImage" v-if="imageList.length < 9">
            <text class="plus">+</text>
            <text class="upload-text">上传附件</text>
          </view>
        </view>
        <text class="upload-tip">(支持格式：jpg、jepg、png格式)</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="button-section">
      <button class="gvr-yellow-button submitbutton" @click="handleSubmit">提交</button>
    </view>
  </view>
</template>

<script setup>
import { ref,onMounted} from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { userApi, fileApi } from '@/service/api.js'
import { userStore } from '@/utils/userStore.js'
import { RouterMethods } from '../../utils/router'
import { formatPhone,validateIdCard} from '@/utils/format'


const formData = ref({
	userInfo: {
		phone:'', //"手机号",
		real_name:'', // 真实姓名
		idnum:'', //二者为null, 代表 用户尚未实名
		gender:'', //性别 0 - 保密  1 - 男, 2 - 女
		main_cert_1:'',
		main_cert_2:'',
		main_cert_3:'',
		main_cert_4:'',
		main_cert_5:''
	},
	images: {
	
	}
})
onMounted(() => {
  console.log('repairer-userInfo onMounted')
  initUserInfo()
})

// 页面显示时检查状态
onShow(() => {
  //console.log("repairer-userInfo onShow")
  //initUserInfo()
})
// 初始化用户信息
const initUserInfo = () => {
  const storedInfo = userStore.getUserInfo()
  if (storedInfo) {
    formData.value = storedInfo
  }
}


const isSubmit = ref(false)

// 证书列表
const certList = {
  main_cert_1: {label: '防爆合格证'},
  main_cert_2: { label: '电工证' },
  main_cert_3: { label: '计量证' },
  main_cert_4: { label: 'GVR培训证' },
  main_cert_5: { label: '石油公司培训证' }
}

const nameInputChange = (e) => {
  isSubmit.value = false 
  console.log(e)
}

const idCardInputChange = (e) => {
  isSubmit.value = false 
  console.log(e)
}


//图片
const imageList = ref([])
//url
const imageUrlList = ref([])

// 模拟上传图片到服务器的方法
const uploadImageToServer = (tempFilePath) => {
	console.log('图片地址====' + tempFilePath)
  return new Promise((resolve) => {
    // 模拟上传延迟
    setTimeout(() => {
      // 模拟服务器返回的图片URL
      const serverUrl = `https://example.com/images/${Date.now()}-${Math.random().toString(36).substr(2, 9)}.jpg`
      resolve(serverUrl)
    }, 500)
  })
}

// 修改选择图片方法
const chooseImage = async () => {
  const remainCount = 9 - imageList.value.length
  if (remainCount <= 0) {
    uni.showToast({ title: '最多上传9张图片', icon: 'none' })
    return
  }
  
  uni.showLoading({ title: '选择图片中...' })
  
  try {
    const res = await new Promise((resolve, reject) => {
      uni.chooseImage({
        count: remainCount,
        success: resolve,
        fail: reject
      })
    })
    console.log(res.tempFilePaths)
    // // 显示上传loading
    // uni.showLoading({ title: '上传中...' })
    
    // 循环上传每张图片
    for (const tempFilePath of res.tempFilePaths) {
        imageList.value.push(tempFilePath)
    }
    
    uni.hideLoading()
  } catch (err) {
    console.error('选择图片失败:', err)
    uni.showToast({ title: '选择图片失败', icon: 'none' })
  }
}

// 修改删除图片方法
const deleteImage = (index) => {
  // 同时删除临时预览
  imageList.value.splice(index, 1)
}

// 修改提交表单方法
const handleSubmit = async () => {
  isSubmit.value = true
  
  // 表单验证
  if (!formData.value?.userInfo?.real_name) {
    uni.showToast({ title: '请输入姓名', icon: 'none' })
    return
  }
  if (!validateIdCard(formData.value?.userInfo?.idnum)) {
    uni.showToast({ title: '请输入身份证号', icon: 'none' })
    return
  }
  if (!formData.value?.userInfo?.gender) {
    uni.showToast({ title: '请选择性别', icon: 'none' })
    return
  }

  try {
    // 显示上传loading
    uni.showLoading({ title: '正在上传图片...' })

    // 如果有图片需要上传
    if (imageList.value.length > 0) {
      // 调用批量上传接口
      const uploadResult = await fileApi.uploadMultiple(imageList.value)
      
      // 上传成功后，将返回的URL按规则存入 formData.images
      if (uploadResult && Array.isArray(uploadResult)) {
        formData.value.images = uploadResult.reduce((acc, url, index) => {
          // 使用 main_comp_ 前缀加序号作为key
          acc[`main_comp_${index + 1}`] = url
          return acc
        }, {})
      }
    }

    // 隐藏上传loading
    uni.hideLoading()
    
    // 显示提交loading
    uni.showLoading({ title: '正在提交信息...' })

     console.log(formData.value)
    // 提交用户信息
    let result = await userApi.commitUserInfo(formData.value.userInfo, formData.value.images)
    if (result.code == undefined) {
      console.log(result)
      userStore.saveUserInfo(result)
      uni.showToast({
        title: '提交信息成功',
        icon: 'none',
        duration: 1000
      })
      setTimeout(() => {
        RouterMethods.toChooseOrg()
      }, 1300)
    } else {
      throw new Error(result.msg || '提交信息失败')
    }
  } catch (err) {
    // 隐藏所有loading
    uni.hideLoading()
    
    uni.showToast({
      title: err.message || '提交信息失败',
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.info-container {
  min-height: 100vh;
  background-color: #FFFFFF;
  padding: 0 56rpx;
  padding-bottom: calc(82rpx + env(safe-area-inset-bottom));
}

.section-title {
  margin-top: 56rpx;
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

.title-text {
  font-family: PingFangSC-Medium;
  font-size: 32rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
}

.form-section {
  background-color: #FFFFFF;
}

.base-form-item {
  display: flex;
  flex-direction: column;
  padding-top:40rpx;
  border-bottom: 2rpx solid #001E32;
}

.base-form-item.active {
  border-bottom: 2rpx solid #BA0C2F;
}

.base-label-box {
  display: flex;
  align-items: center;
  margin-bottom: 26rpx;
}

.required {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #BA0C2F;
  letter-spacing: 0;
  font-weight: 500;
}

.label {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
}

.fail-label {
  font-family: PingFangSC-Medium;
  font-size: 24rpx;
  color: #BA0C2F;
  letter-spacing: 0;
  font-weight: 500;
}

.input {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
  margin-bottom: 8rpx
}

.phone-text {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #001E32;
  letter-spacing: 0;
  font-weight: 500;
  margin-bottom: 8rpx
}

.form-gender-group-item {
  display: flex;
  flex-direction: column;
  padding-top: 40rpx;
}
.gender-group {
  display: flex;
  justify-content: space-between;
  width: 516rpx;
}

.gender-item {
  width: 156rpx;
  height: 64rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #DEDEDE;
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #000000;
  letter-spacing: 0;
  text-align: center;
  font-weight: 500;
}

.gender-item.active {
  background: #285789;
  color: #FFFFFF;
}

.cert-form-item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding-top: 28rpx;
}
.cert-label-box {
  display: flex;
  align-items: center;
  padding-left: 28rpx;
}

.cert-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 336rpx;
}

.cert-item {
  width: 156rpx;
  height: 64rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #DEDEDE;
  font-family: PingFangSC-Medium;
  font-size: 32rpx;
  color: #000000;
  letter-spacing: 0;
  text-align: center;
  font-weight: 500;
}

.cert-item.active {
  background: #285789;
  color: #FFFFFF;
}

.upload-section {
  padding: 32rpx 0;
}

.upload-title {
  font-family: PingFangSC-Medium;
  font-size: 28rpx;
  color: #000000;
  letter-spacing: 0;
  font-weight: 500;
}

.upload-area {
  margin-top: 14rpx;
  display: grid;
  grid-template-columns: repeat(3,1fr);
  gap:30rpx;
  padding: 5rpx;
  margin-bottom: 16rpx;
}

.upload-preview {
  width: 190rpx;
  height: 190rpx;
  position: relative;
  border-radius: 4rpx;
  overflow: hidden;
  border: 2rpx solid #001E32;
}

.upload-preview image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 32rpx;
  height: 32rpx;
  background: rgba(0, 0, 0, 0.4);
  color: #FFFFFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
}

.upload-btn {
  width: 190rpx;
  height: 190rpx;
  background: #FFFFFF;
  border: 2rpx solid #001E32;
  border-radius: 4rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
}

.plus {
  font-size: 70rpx;
  color: #001E32;
  line-height: 1;
}

.upload-text {
  font-family: PingFangSC-Regular;
  font-size: 24rpx;
  color: #B5B5B5;
  letter-spacing: 0;
  text-align: center;
  font-weight: 400;
}

.upload-tip {
  font-family: PingFangSC-Medium;
  font-size: 20rpx;
  color: #B5B5B5;
  letter-spacing: 0;
  font-weight: 500;
}

.button-section {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #FFFFFF;
}
.submitbutton {
  border-radius: 0;
}



</style> 